package com.init.iblog.runner;

import com.init.iblog.constants.SystemConstants;
import com.init.iblog.domain.entity.Blog;
import com.init.iblog.mapper.BlogMapper;
import com.init.iblog.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 项目启动时，执行方法
 * 应用了redis需要启动redis服务，否则会报错
 */
@Component
public class ViewCountRunner implements CommandLineRunner {

    @Autowired(required = false)
    private BlogMapper blogMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public void run(String... args) throws Exception {

        //查询博客信息：id、viewCount
        List<Blog> blogs = blogMapper.selectList(null);
        Map<String,Integer> viewCountMap = blogs.stream()
                .collect(Collectors.toMap(blog -> blog.getId().toString(),blog->{
                    return blog.getViewCount().intValue();
                }));
        //存储到redis中

        redisCache.setCacheMap(SystemConstants.BLOG_VIEW_COUNT,viewCountMap);
    }
}
